package com.zhang.user.api;

import com.zhang.dubbo.api.user.UserRpcApi;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserApi {

    @Reference
    private UserRpcApi userService;

    @GetMapping("/register/{email}/{password}/{code}")
    public String register(@PathVariable(value = "email") String email,
                           @PathVariable(value = "password") String password,
                           @PathVariable(value = "code") String code,
                           HttpServletResponse response) {
        String result = userService.register(email, password, code);
        if (!result.equals("false")) {
            Cookie cookie = new Cookie("token", result);
            cookie.setPath("/");
            cookie.setMaxAge(3600);
            response.addCookie(cookie);
            return "true";
        } else {
            return "false";
        }
    }

    @GetMapping("/registered/{email}")
    public String registered(@PathVariable(value = "email") String email) {
        return userService.registered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable(value = "email") String email,
                        @PathVariable(value = "password") String password,
                        HttpServletResponse response) {
        String result = userService.login(email, password);
        if (result.equals("false")) {
            return "false";
        } else {
            Cookie cookie = new Cookie("token", result);
            cookie.setPath("/");
            cookie.setMaxAge(3600);
            response.addCookie(cookie);
            cookie.setDomain("www.cloudscnone.com");
            response.setHeader("Access-Control-Allow-Credentials","true");
            return "true";
        }
    }

    @GetMapping("/getEmail/{token}")
    public String getEmail(@PathVariable(value = "token") String token) {
        return userService.getInfo(token);
    }
}
